package geektime.spring.springbucks.filter;

import com.alibaba.druid.filter.FilterChain;
import com.alibaba.druid.filter.FilterEventAdapter;
import com.alibaba.druid.proxy.jdbc.PreparedStatementProxy;
import com.alibaba.druid.sql.SQLUtils;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlInsertStatement;
import com.alibaba.druid.util.JdbcConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import java.sql.SQLException;
import java.util.List;

@Slf4j
public class CustomLogFilter extends FilterEventAdapter {
    final static String DB_TYPE = JdbcConstants.H2;

    public boolean preparedStatement_execute(FilterChain chain, PreparedStatementProxy statement) throws SQLException {
        try{
            List<SQLStatement> stmtList = SQLUtils.parseStatements(statement.getSql(), DB_TYPE);
            if(!CollectionUtils.isEmpty(stmtList)){
                SQLStatement sqlStatement = stmtList.get(0);
                int stmtSize = stmtList.size();
                if(stmtSize >10){
                    throw new SQLException(String.format("SQL 分割条数为 %s，超过 10 条限制，具体 SQL（只获取第一条）：%s" , stmtSize,sqlStatement));
                }

                if(sqlStatement instanceof MySqlInsertStatement){
                    MySqlInsertStatement insertStatement= (MySqlInsertStatement) sqlStatement;
                    int valueSize = insertStatement.getValuesList().size();
                    if(!CollectionUtils.isEmpty(insertStatement.getValuesList())&& valueSize >10){
                        throw new SQLException(String.format("插入 SQL values 分割条数为 %s，超过 10 条限制，具体 SQL：%s", valueSize,sqlStatement));
                    }
                }
            }
        }catch (SQLException e){
            log.error("CustomLogFilter：执行 SQL 规则过滤器校验不通过！",e);
        }
        catch (Exception e){
            log.error("CustomLogFilter：执行 SQL 规则过滤器失败！",e);
        }
        return super.preparedStatement_execute(chain, statement);
    }
}